import { createApp, h } from 'vue'
import MessageTip from './index.vue'
import event from '../eventCenter'
// 存储所有消息提示实例的容器
const messageInstances = []

function showMessage(messageText, type, duration) {
  // 创建容器
  const container = document.createElement('div')
  document.body.appendChild(container)

  // 创建组件实例
  const app = createApp({
    render() {
      return h(MessageTip, {
        message: messageText,
        type,
        duration,
        onClose: () => {
          removeMessageInstance(container)
        }
      })
    }
  })

  // 挂载组件
  app.mount(container)

  // 将容器添加到实例列表中
  messageInstances.push(container)

  // 动态计算每个消息提示的位置
  const topOffset = (messageInstances.length - 1) * 60 + 10 // 每个消息提示间隔60px，初始位置20px
  container.style.top = `${topOffset}px`
  container.style.left = '50%'
  container.style.transform = 'translateX(-50%)'
  container.style.position = 'fixed'
  container.style.zIndex = '9999'
  // 自动关闭消息提示
  if (duration > 0) {
    setTimeout(() => {
      removeMessageInstance(container)
    }, duration)
  }

  // 返回关闭函数，以便外部可以手动关闭
  return () => removeMessageInstance(container)
}

function removeMessageInstance(container) {
  const index = messageInstances.indexOf(container)
  if (index !== -1) {
    // 卸载 Vue 应用实例并移除容器
    const app = messageInstances[index].__vue_app__
    setTimeout(() => {
      if (app) {
        app.unmount()
      }
      document.body.removeChild(container)
    }, 1000)

    messageInstances.splice(index, 1)
    // 更新剩余的消息提示框的位置
    for (let i = index; i < messageInstances.length; i++) {
      const instance = messageInstances[i]
      instance.topOffset = i * 60 + 10
      instance.style.top = `${instance.topOffset}px`
    }
  }
}

const message = {
  success: (text, duration = 3000) => showMessage(text, 'success', duration),
  error: (text, duration = 3000) => showMessage(text, 'error', duration),
  warning: (text, duration = 3000) => showMessage(text, 'warning', duration),
  info: (text, duration = 3000) => showMessage(text, 'info', duration),
  closeAll: () => {
    messageInstances.forEach(instance => removeMessageInstance(instance))
  }
}

event.on('RELOGIN', () => {
  message.warning('身份验证过期，请重新登陆！')
})

// 导出 message 对象
export default {
  message,
  install: app => {
    app.config.globalProperties.$message = message
    // 提供给 inject 使用
    app.provide('message', message)
  }
}
